﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SHAManagedBase.cs" company="Marcin Jastrzebski">
//   Copyright (c) Marcin Jastrzebski (marcin@marcinj.net)
// </copyright>
// <summary>
//   The sha managed base.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace KeePassLib
{
    using System.Runtime.InteropServices.WindowsRuntime;

    using Windows.Security.Cryptography.Core;
    using Windows.Storage.Streams;

    /// <summary>The SHA managed base.</summary>
    /// <remarks>This class is intended to mimic the behavior of SHA*Managed classes from .net.</remarks>
    public abstract class SHAManagedBase
    {
        #region Fields

        /// <summary>The algorithm.</summary>
        private readonly HashAlgorithmProvider algorithm;

        #endregion

        #region Constructors and Destructors

        /// <summary>Initializes a new instance of the <see cref="SHAManagedBase"/> class.</summary>
        /// <param name="algorithmName">The algorithm name.</param>
        protected SHAManagedBase(string algorithmName)
        {
            this.algorithm = HashAlgorithmProvider.OpenAlgorithm(algorithmName);
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>Computes the hash for the specified buffer.</summary>
        /// <param name="buffer">The buffer.</param>
        /// <returns>The hash value.</returns>
        public byte[] ComputeHash(byte[] buffer)
        {
            return this.ComputeHash(buffer.AsBuffer());
        }

        /// <summary>Computes the hash for the specified portion of the buffer.</summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The offset in the buffer where to start.</param>
        /// <param name="count">The number of bytes starting from offset to hash.</param>
        /// <returns>The hash value.</returns>
        public byte[] ComputeHash(byte[] buffer, int offset, int count)
        {
            IBuffer subset = buffer.AsBuffer(offset, count);
            return this.ComputeHash(subset);
        }

        #endregion

        #region Methods

        /// <summary>The compute hash for the specified buffer.</summary>
        /// <param name="buffer">The buffer.</param>
        /// <returns>The hash value.</returns>
        private byte[] ComputeHash(IBuffer buffer)
        {
            byte[] result = this.algorithm.HashData(buffer).ToArray();
            return result;
        }

        #endregion
    }
}